package com.colis.quartz.common.extension;

import com.colis.quartz.annotation.RMpController;
import com.colis.quartz.common.base.BaseBean;
import com.colis.quartz.common.base.PageParam;
import com.colis.quartz.common.base.PageResult;
import com.colis.quartz.common.base.RestResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;


/**
 * <p> 描述：基础接口管理 </p>
 *
 * @author wlp
 * @version 1.0.0
 * @date 2021/12/10 9:16
 */
@Api(tags = "基础接口管理")
@RMpController("/base/{model}")
public class MyBaseController<T extends BaseBean> extends BaseController<T> {

    @Operation(summary = "分页查询数据")
    @PostMapping
    @ApiImplicitParam(name = "model", value = "模块名称（实体类名称）", dataTypeClass = String.class, required = true)
    protected RestResult<PageResult<T>> pageList(@Valid @RequestBody PageParam param, @PathVariable String model) {
        PageResult<T> pageResult = getService(model).pageList(param);
        return RestResult.success(pageResult);
    }

    @Operation(summary = "根据id查询数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id主键", dataTypeClass = Long.class, required = true),
            @ApiImplicitParam(name = "model", value = "模块名称（实体类名称）", dataTypeClass = String.class, required = true)
    })
    @GetMapping("getOne")
    protected RestResult<T> getOne(Long id, @PathVariable String model) {
        Optional<T> one = getService(model).getOne(id);
        if (one.isEmpty()) {
            return RestResult.fail(null);
        }
        return RestResult.success(one.get());
    }

    @Operation(summary = "新增或更新数据")
    @PutMapping
    @ApiImplicitParam(name = "model", value = "模块名称（实体类名称）", dataTypeClass = String.class, required = true)
    protected RestResult<T> save(@RequestBody T bean, @PathVariable String model) {
        return RestResult.success(getService(model).saveOrUpdate(bean));
    }

    @Operation(summary = "根据id删除数据")
    @DeleteMapping("{id}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id主键", dataTypeClass = Long.class, required = true),
            @ApiImplicitParam(name = "model", value = "模块名称（实体类名称）", dataTypeClass = String.class, required = true)
    })
    protected RestResult<List<T>> del(@PathVariable Long id, @PathVariable String model) {
        getService(model).deleteById(id);
        return RestResult.success();
    }
}
